<template>
  <div class="app-container">
    <br>
    <br>
    <el-button type="primary" @click="add">申请采购</el-button>
    <br>
    <br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="采购单号" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column label="采购类型" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>
      <el-table-column label="采购部门" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.deptName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品类数量" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.drugTypeNum }}
        </template>
      </el-table-column>
      <el-table-column label="总数量" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.drugNum }}
        </template>
      </el-table-column>
      <el-table-column label="采购时间" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.createdTime.split(' ')[0] }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusColorFilter">{{ scope.row.status | statusNameFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" align="center" width="300" >
        <template slot-scope="scope">
          <el-button type="primary" :loading="toInfoBtnLoading"  @click="getInfo(scope.row)" size="small">详情</el-button>
          <el-button type="success" :loading="toUpdateBtnLoading" @click="update(scope.row)" size="small" v-if="scope.row.status === 0">修改</el-button>
          <el-button type="warning" :loading="toUpdateBtnLoading" v-if="scope.row.canAudit" @click="approve(scope.row, true)" size="small">审批</el-button>
          <el-button type="danger" :loading="toUpdateBtnLoading" v-if="scope.row.canAudit" @click="approve(scope.row, false)" size="small">拒绝</el-button>
          <el-button type="info"  @click="toCopy(scope.row)" size="small">复制</el-button>
          <!-- <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="->, total, prev, pager, next"
      :total="this.total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="clickCurPage"
      >
    </el-pagination>
  <el-dialog title="采购详情" :visible.sync="infoVisible" width="1800px">
    <h2>基本信息</h2>
    <el-form ref="info" :model="info" label-width="80px">
      <el-form-item label="采购单号">
          <el-input v-model="info.code" :disabled="true" />
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="采购类型">
              <el-input v-model="info.type" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="供货商">
            <el-select v-model="info.supplier" placeholder="请选择" style="width: 100%" :disabled="true">
              <el-option
                v-for="item in suppliers"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="库房">
            <el-select v-model="info.applyDepository" placeholder="请选择" style="width: 100%" :disabled="true">
              <el-option
                v-for="item in depositoryEnum"
                :key="item.id"
                :label="item.name + ' ' + ' (' + item.deptName + ')'"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="品类数量">
              <el-input v-model="info.drugTypeNum" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="总数量">
              <el-input v-model="info.drugNum" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter=10>
        <el-col :span=8 >
          <el-form-item :label="(index+1)+'级审批'" v-for="(jobDuty, index) in this.auditPreset" :key="jobDuty.id">
            <span>{{ jobDuty.name }}</span>
            <el-select v-model="jobDuty.auditUser" placeholder="请选择" style="width: 100%" :disabled="true">
              <el-option
                v-for="item in jobDuty.auditAvailableUserList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <h3>采购药品</h3>
      <el-form-item label="药品" >
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <el-form-item v-for="(drug, drugIndex) in info.purchaseOrderDrugList" :key="drugIndex" style="border-bottom: 1px solid #E4E7ED;">
            <div v-for="(opt, optIndex) in drug.operationList" :key="optIndex">
              <div style="display: flex;flex-direction: row;width: 100%;padding: 5px;" v-if="drug.godownDrugList.length === 0">
                <div class="drug-name">{{drug.drugName + ' ' + drug.form + ' ' + drug.drugSpecs}}</div>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">{{'采购数量(' + drug.outerUnit + ')'}}</span>
                  <el-input type="Number" min=0 class="drug-input" v-model="opt.num" :disabled="true"></el-input>
                </div>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">库存数量</span>
                  <el-input class="drug-input" v-model="drug.sourceNum" :disabled="true"></el-input>
                </div>
              </div>
              <div style="display: flex;flex-direction: row;width: 100%;padding: 5px;" v-for="(godown, godownIndex) in drug.godownDrugList" :key="godownIndex" >
                <div class="drug-name" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}" >{{drug.drugName + ' ' + drug.form + ' ' + drug.drugSpecs}}</div>
                <div class="drugs-item" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}" >
                  <span class="drugs-item-title" style="width: 140px;">{{'采购数量(' + drug.outerUnit + ')'}}</span>
                  <el-input type="Number" min=0 class="drug-input" v-model="opt.num" :disabled="true">
                  </el-input>
                </div>
                <div class="drugs-item" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}">
                  <span class="drugs-item-title" style="width: 140px;">库存数量</span>
                  <el-input class="drug-input" v-model="drug.sourceNum" :disabled="true"></el-input>
                </div>
                <div class="drugs-item" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}">
                  <span class="drugs-item-title" style="width: 140px;">最低采购量</span>
                  <el-input class="drug-input" v-model="drug.minPurchaseNum" :disabled="true"></el-input>
                </div>
                <div class="drugs-item" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}">
                  <span class="drugs-item-title" style="width: 140px;">采购周期</span>
                  <el-input class="drug-input" v-model="drug.buyCycle" :disabled="true"></el-input>
                </div>
                <el-divider direction="vertical"></el-divider>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">批号</span>
                  <el-input class="drug-input" v-model="godown.batchCode" :disabled="true" ></el-input>
                </div>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">生产日期</span>
                  <el-date-picker v-model="godown.productTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 140px;margin-right: 10px;" :disabled="true" ></el-date-picker>
                </div>
                <div class="drugs-item" >
                  <span class="drugs-item-title" style="width: 140px;">保质期（月）</span>
                  <el-input class="drug-input" v-model="godown.qualityTime" :disabled="true" ></el-input>
                </div>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">有效期至</span>
                  <el-date-picker v-model="godown.expirationTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 140px;margin-right: 10px;" :disabled="true" ></el-date-picker>
                </div>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">入库数量</span>
                  <el-input type="Number" min=0 class="drug-input" v-model="godown.godownNum" :disabled="true" ></el-input>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog :title="dialogTitle" :visible.sync="formVisible" width="1800px" :close-on-click-modal="false" >
    <h2>基本信息</h2>
    <el-form ref="form" :model="form" label-width="80px" :rules="formRules">
      <el-form-item label="采购单号" v-if="form.code != '---'">
          <el-input v-model="form.code" :disabled="true" />
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="采购类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择" style="width: 100%"  :disabled="true">
              <el-option
                v-for="item in typeEnum"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="供货商" prop="supplier">
            <el-select v-model="form.supplier" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in suppliers"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="库房" prop="dept">
            <el-select v-model="form.applyDepository" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in depositoryEnum"
                :key="item.id"
                :label="item.name + ' ' + ' (' + item.deptName + ')'"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="品类数量">
              <el-input v-model="form.drugTypeNum" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="总数量">
              <el-input v-model="form.drugNum" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter=10>
        <el-col :span=8 >
          <el-form-item :label="(index+1)+'级审批'" v-for="(jobDuty, index) in this.auditPreset" :key="jobDuty.id" prop="auditPreset">
            <span>{{ jobDuty.name }}</span>
            <el-select v-model="jobDuty.auditUser" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in jobDuty.auditAvailableUserList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      
      <h3>采购药品</h3>
      <el-form-item label="搜索药品">
        <el-autocomplete
          :disabled="form.applyDepository === undefined"
          value-key="pinyinCode"
          class="inline-input"
          v-model="searchValue"
          :fetch-suggestions="querySearch"
          placeholder="请输入 拼音简码"
          :trigger-on-focus="false"
          @select="handleSelect"
          style="width: 100%;"
        >
        <template slot-scope="{ item }">
          <span >{{ item.name+'/' }}</span>
          <span >{{ item.commonName+' ' }}</span>
          <span >{{ item.form+' ' }}</span>
          <span >{{ item.specs+' '  }}</span>
          <span >{{ item.factory }}</span>
        </template>
        </el-autocomplete>
      </el-form-item>
      
      <el-form-item label="药品">
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <el-form-item v-for="(drug, drugIndex) in form.purchaseOrderDrugList" :key="drugIndex" style="border-bottom: 1px solid #E4E7ED;" >
            <div v-for="(opt, optIndex) in drug.operationList" :key="optIndex">
              <div style="display: flex;flex-direction: row;width: 100%;padding: 5px;" v-if="drug.godownDrugList.length === 0">
                <div class="drug-name">{{drug.drugName + ' ' + drug.form + ' ' + drug.drugSpecs}}</div>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">{{'采购数量(' + drug.outerUnit + ')'}}</span>
                  <el-input type="Number" min=0 class="drug-input" v-model="opt.num" @input="inputDrugNum" @blur="checkMin(opt, drug)" :disabled="form.status != 0"></el-input>
                </div>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">库存数量</span>
                  <el-input class="drug-input" v-model="drug.sourceNum" :disabled="true"></el-input>
                </div>
                <div style="display: flex;flex-direction: column;justify-content: center;margin-right: 5px;" >
                  <el-button type="danger" circle style="width: 20px;height: 20px;align-items: center;display: flex;justify-content: center;" @click="delDrugGodown(drug, drugIndex, 0)">-</el-button>
                </div>
              </div>
              <div style="display: flex;flex-direction: row;width: 100%;padding: 5px;" v-for="(godown, godownIndex) in drug.godownDrugList" :key="godownIndex" >
                <div class="drug-name" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}" >{{drug.drugName + ' ' + drug.form + ' ' + drug.drugSpecs}}</div>
                <div class="drugs-item" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}" >
                  <span class="drugs-item-title" style="width: 140px;">{{'采购数量(' + drug.outerUnit + ')'}}</span>
                  <el-input type="Number" min=0 class="drug-input" v-model="opt.num" :disabled="godownIndex!=0 || form.status != 0" @input="inputDrugNum" @blur="checkMin(opt, drug)"></el-input>
                </div>
                <div class="drugs-item" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}">
                  <span class="drugs-item-title" style="width: 140px;">库存数量</span>
                  <el-input class="drug-input" v-model="drug.sourceNum" :disabled="true"></el-input>
                </div>
                <div class="drugs-item" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}">
                  <span class="drugs-item-title" style="width: 140px;">最低采购量</span>
                  <el-input class="drug-input" v-model="drug.minPurchaseNum" :disabled="true"></el-input>
                </div>
                <div class="drugs-item" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}">
                  <span class="drugs-item-title" style="width: 140px;">采购周期</span>
                  <el-input class="drug-input" v-model="drug.buyCycle" :disabled="true"></el-input>
                </div>
                <el-divider direction="vertical"></el-divider>
                <div class="drugs-item" v-if="form.code != '---' && form.godownStatus === 0">
                  <span class="drugs-item-title" style="width: 140px;">批号</span>
                  <el-input class="drug-input" v-model="drug.batchCode" :disabled="true"></el-input>
                </div>
                <div class="drugs-item" v-if="form.code != '---'&& form.godownStatus === 0">
                  <span class="drugs-item-title" style="width: 140px;">生产日期</span>
                  <el-date-picker v-model="godown.productTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 140px;margin-right: 10px;" :disabled="true"></el-date-picker>
                </div>
                <div class="drugs-item" v-if="form.code != '---'&& form.godownStatus === 0">
                  <span class="drugs-item-title" style="width: 140px;">保质期（月）</span>
                  <el-input class="drug-input" v-model="godown.qualityTime" :disabled="true" ></el-input>
                </div>
                <div class="drugs-item" v-if="form.code != '---'&& form.godownStatus === 0">
                  <span class="drugs-item-title" style="width: 140px;">有效期至</span>
                  <el-date-picker v-model="godown.expirationTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 140px;margin-right: 10px;" :disabled="true"></el-date-picker>
                </div>
                
                <div style="display: flex;flex-direction: column;justify-content: center;margin-right: 5px;" >
                  <el-button type="danger" circle style="width: 20px;height: 20px;align-items: center;display: flex;justify-content: center;" @click="delDrugGodown(drug, drugIndex, godownIndex)">-</el-button>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="warning" :loading="commitBtnLoading" @click="confirm(0)">存草稿</el-button>
        <div style="width:200px;display: inline-block;"> </div>
        <el-button type="primary" :loading="commitBtnLoading" @click="confirm(1)">提交</el-button>
        <div style="width:100px;display: inline-block;"> </div>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script>
import { getList, getInfo, addorupdate, del } from '@/api/purchaseOrder'
import { getListByPinyinCode, queryByCodeAnDepositoryId } from '@/api/drug'
import { getList as getSupplierList } from '@/api/supplier'
import { getChildrenDepositoryList } from '@/api/store'
import { getList as getStoreList } from '@/api/store'
import { stringToDate } from '@/utils/dateUtil'
import { audit, getList as getAuditList, getInfo as getAuditInfo } from '@/api/auditFlow'

export default {
  filters: {
    statusColorFilter(status) {
      const statusMap = ['success', 'warning', 'primary', 'danger']
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusMap = ['草稿', '待审批', '审批完成', '已拒绝']
      return statusMap[status]
    }
  },
  data() {
    const validatePlan = (rule, value, callback) => {
      if (!value) callback(new Error('请填写计划名称')) 
      else callback()
    }
    const validateType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型'))
      else callback()
    }
    const validateDept = (rule, value, callback) => {
      if (!this.form.applyDepository) callback(new Error('请选择库'))
      else callback()
    }
    const validateSupplier = (rule, value, callback) => {
      if (!this.form.supplier) callback(new Error('请选择供货商'))
      else callback()
    }
    const validateAuditPreset = (rule, value, callback) => {
      for (let index = 0; index < this.auditPreset.length; index++) {
        if(!this.auditPreset[index].auditUser) callback(new Error('请选择审批人'))
      }
      callback()
    }
    return {
      list: null,
      listLoading: true,
      toUpdateBtnLoading: false,
      toInfoBtnLoading: false,
      commitBtnLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 20,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      dialogTitle: '',
      info: {},
      form: {},
      purchaseOrderDrugList: [],
      typeEnum: ["集中", "临时"],
      depositoryEnum: [],
      suppliers: [],
      query: {},
      tagEnum: [{id: 1, name: '热销'},{id: 2, name: '促销'}],
      dugTypeTreeList: [],
      formRules: {
        plan: [{ required: true, trigger: 'blur', validator: validatePlan }],
        type: [{ required: true, trigger: 'blur', validator: validateType }],
        dept: [{ required: true, trigger: 'blur', validator: validateDept }],
        supplier: [{ required: true, trigger: 'blur', validator: validateSupplier }],
        auditPreset: [{ required: true, trigger: 'blur', validator: validateAuditPreset }],
      },
      searchValue: '',
      auditPreset: [],
    }
    
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      var loginInfo = this.$store.getters.userInfo.loginInfo
      var deptId = loginInfo.loginDept.deptId
      const reqBody = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          deptId: deptId,
          type: '临时'
      }
      getList(reqBody).then(response => {
        console.log(response)
        this.list = response.data.records
        this.list.forEach(item=>{
          if(item.auditStatus != undefined) {
            item.status = item.auditStatus
          }
        })
        this.total = response.data.total
        this.listLoading = false
        
      })
      getSupplierList().then(supplierRes => {
        console.log(supplierRes)
        this.suppliers = supplierRes.data
      })
      getAuditInfo({businessCode: 'purchase_order'}).then(res=> {
        this.auditPreset = res.data
      })
      getChildrenDepositoryList(deptId).then(deptRes=> {
        this.depositoryEnum = deptRes.data
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    add() {
      this.reset()
      this.dialogTitle = '申请采购单'
      this.form.code = '---'
      this.form.drugTypeNum = 0
      this.form.drugNum = 0
      this.form.status = 0
      this.form.type = "临时"
      this.$set(this.form, 'purchaseOrderDrugList', [])
      this.$set(this.form, 'operationList', [])
      getAuditInfo({businessCode: 'purchase_order'}).then(res=> {
        this.auditPreset = res.data
      })
      this.formVisible = true
    },
    getInfo(row) {
      this.toInfoBtnLoading = true
      getInfo(row.id).then(infoRes=>{
        console.log(infoRes)
        this.info = infoRes.data
        this.auditPreset = infoRes.data.auditFlowDetail.jobDutyList
        this.infoVisible = true
        this.toInfoBtnLoading = false
        this.calculateExpirationTime(this.info)
      })
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改采购单'
      this.toUpdateBtnLoading = true
      getInfo(row.id).then(infoRes=>{
        console.log(infoRes)
        this.form = JSON.parse(JSON.stringify(infoRes.data))
        this.auditPreset = infoRes.data.auditFlowDetail.jobDutyList
        this.toUpdateBtnLoading = false
        this.calculateExpirationTime(this.form)
        if(!this.form.operationList) this.$set(this.form, 'operationList', [])
        this.formVisible = true
      })
    },
    toCopy(row) {
      getInfo(row.id).then(infoRes=>{
        console.log(infoRes)
        this.form = JSON.parse(JSON.stringify(infoRes.data))
        this.form.id = undefined
        this.form.status = 0
        this.form.purchaseOrderDrugList.forEach(purchase=>{
          purchase.godownDrugList = []
        })
        this.toUpdateBtnLoading = false
        this.calculateExpirationTime(this.form)
        if(!this.form.operationList) this.$set(this.form, 'operationList', [])
        this.formVisible = true
      })
    },
    calculateExpirationTime(form) {
      form.purchaseOrderDrugList.forEach(drugItem=> {
        drugItem.godownDrugList.forEach(godown=> {
          if(godown.productTime != undefined) {
            var productTime = stringToDate(godown.productTime)
            var productYear = productTime.getFullYear();
            var productMonth = productTime.getMonth();
            var expirationTime = stringToDate(godown.expirationTime)
            var expirationYear = expirationTime.getFullYear();
            var expirationMonth = expirationTime.getMonth();
            this.$set(godown, 'qualityTime', expirationMonth - productMonth + (expirationYear - productYear)*12)
          }
        })
      })
    },
    deleteInfo(scope) {
      this.$confirm('确定删除该职务?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.list.splice(scope.$index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    confirm(type) {
      this.commitBtnLoading = true
      this.form.auditUserIds = this.auditPreset.map(jobDutyVo => Number(jobDutyVo.auditUser))
      console.log(this.form)
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          this.form.status = type
          addorupdate(this.form).then(res=>{
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.commitBtnLoading = false
            this.formVisible = false
            this.listLoading = false
            this.$tab.refreshPage({path: '/store/purchaseOrder', name: "purchaseOrder"});
          }).catch(err=>{
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          this.commitBtnLoading = false
          return false
        }
      })
    },
    cancel() {
      this.infoVisible = false
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    querySearch(queryString, cb) {
      getListByPinyinCode(queryString, this.form.applyDepository).then(drugListRes=>{
        // 调用 callback 返回建议列表的数据
        cb(drugListRes.data);
      })
    },
    handleSelect(item) {
      if(this.form.purchaseOrderDrugList.map(drugItem => drugItem.drugCode).indexOf(item.code) != -1) {
        this.$message.error('药品已存在');
        return;
      }
      this.searchValue = item.name + '/' + item.commonName + ' ' + item.form + ' ' + item.specs + ' ' + item.factory
      queryByCodeAnDepositoryId({drugCode: item.code, depositoryId: this.form.applyDepository}).then(res=> {
      console.log("res", res)
        var inputNum = 0
        var purchaseOrder = {
          drugCode: item.code,
          drugName: item.name,
          drugCommonName: item.commonName,
          drugSpecs: item.specs,
          status: item.status,
          factory: item.factory,
          form: item.form,
          outerUnit: item.outerUnit,
          num: inputNum,
          minPurchaseNum: item.minPurchaseNum,
          buyCycle: item.buyCycle,
          depositoryId: this.form.applyDepository,
          depositoryName: this.getDepositoryName(this.form.applyDepository),
          godownDrugList: [{
            drugCode: item.code,
            num: 0,
            expirationTime: '',
            productTime: '',
          }],
          drugDepositoryVoList: [{
            id: this.form.applyDepository,
            name: this.getDepositoryName(this.form.applyDepository), 
            sourceNum: res.data ? res.data.inventory : 0,
            doneInventory: res.data ? res.data.inventory : 0,
          }],
        }
        this.$set(purchaseOrder, 'operationList', [{
          drugCode: item.code,
          num: inputNum,
          operationType: 2,
          targetDepositoryId: this.form.applyDepository,
        }])
        var sourceNum = purchaseOrder.drugDepositoryVoList.filter(dep=> dep.id === this.form.applyDepository)[0].inventory
        purchaseOrder.sourceNum = sourceNum?sourceNum:0
        this.form.purchaseOrderDrugList.push(purchaseOrder)
        console.log(this.form.purchaseOrderDrugList)
        this.form.drugTypeNum++
      })
    },
    delDrugGodown(drug, drugIndex, godownIndex) {
      if(godownIndex === 0) {
        this.form.purchaseOrderDrugList.splice(drugIndex, 1)
        this.form.drugTypeNum--
      } else {
        drug.godownDrugList.splice(godownIndex, 1)
      }
      this.form.drugNum = this.form.purchaseOrderDrugList.reduce((sum, obj) => Number(sum) + Number(obj.num), 0);
    },
    inputDrugNum() {
      this.form.drugNum = this.form.purchaseOrderDrugList.reduce((sum, obj) => Number(sum) + Number(obj.num), 0);
      console.log(this.form.purchaseOrderDrugList)
    },
    approve(row, pass) {
      console.log(row)
      this.toUpdateBtnLoading = true
      audit({flowNo: row.code, pass: pass}).then(auditRes=> {
        console.log("auditRes", auditRes)
        this.toUpdateBtnLoading = false
        this.fetchData()
      })
    },
    checkMin(opt, drug) {
      if(opt.num < drug.minPurchaseNum) {
        this.$message.error('低于最低采购量,已自动计算');
        opt.num = drug.minPurchaseNum
        this.form.drugNum = this.form.purchaseOrderDrugList.reduce((sum, obj) => Number(sum) + Number(obj.num), 0);
      }
    },
    selectAuditUser() {

    },
    getDepositoryName(id) {
      return this.depositoryEnum.filter(dep => dep.id === id)[0].name
    }
  }
}

</script>

<style>
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .drug-input {
    width: 100%;
    display: inline-block;
    margin-right: 10px;
  }
  .drugs-item-title {
    line-height: 20px;
    text-align: center;
    background-color: #E4E7ED;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  .drugs-item {
    width: 140px;
    display: flex;
    flex-direction: column;
    margin-right: 10px;
  }
  .drug-name {
    width: 300px;
    word-wrap: break-word;
    margin-right: 20px;
    font-size: 15px;
    height: 58px;
    line-height: 58px;
  }
</style>